<template>
  <div class="in">
    <div class="tit">
      <div class="ul1">
        <div>地址管理</div>
      </div>
      <div class="ul2"
           @click="editAddress(0)">
        添加地址
      </div>
    </div>
    <div class="qie">
      <div class="one">
        共存了{{adsList.length}}条地址
      </div>
      <div class="tab">
        <el-table :data="adsList"
                  style="width: 100%">
          <el-table-column prop="fullName"
                           label="收货人"
                           align="center">
          </el-table-column>
          <el-table-column label="所在地区"
                           align='center'>
            <template slot-scope="scope">
              <div>{{scope.row.province}} {{scope.row.city}} {{scope.row.county}}</div>
            </template>
          </el-table-column>
          <el-table-column label="详细地址"
                           prop="address"
                           align='center'>
          </el-table-column>
          <el-table-column label="电话号码"
                           prop="phone"
                           align='center'>
          </el-table-column>
          <el-table-column label="操作"
                           align='center'>
            <template slot-scope="scope">
              <el-button size="mini"
                         @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini"
                         type="danger"
                         @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column label="默认"
                           align='center'>
            <template slot-scope="scope">
              <el-button v-if='scope.row.defaultValue=="0"'
                         size="mini"
                         type="info">默认地址</el-button>
              <el-button v-else
                         size="mini"
                         type="success"
                         @click="moren(scope.row)">设置默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog title="收货地址"
               :visible.sync="dialogFormVisible">
      <el-form :model="form"
               label-width="100px"
               class="form1">
        <el-form-item label="选择城市"
                      :required="true">
          <el-cascader placeholder="请选择地区"
                       :options="options"
                       v-model="form.provinceCityArea"
                       @change="changeCity"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址"
                      :required="true">
          <el-input v-model="form.address"
                    placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="姓名"
                      :required="true">
          <el-input v-model="form.fullName"
                    placeholder="请输入收件人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号"
                      :required="true">
          <el-input v-model="form.phone"
                    placeholder="请输入收件人手机号"></el-input>
        </el-form-item>
        <el-form-item label="是否默认">
          <el-radio-group v-model="form.default"
                          @change="alog">
            <el-radio label="0">是</el-radio>
            <el-radio label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="cancleSubmit">取 消</el-button>
        <el-button type="primary"
                   @click="adsSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import arr from "@/assets/js/districts";
export default {
  data() {
    return {
      adsList: [], // 地址列表
      form: {
        provinceCityArea: "",
        address: '',
        province: "",
        city: "",
        county: "",
        fullName: '',
        phone: '',
        default: "1"
      },
      dialogFormVisible: false,//修改、增加地址弹框
      options: [], // 省市区
      selectedOptions: [],
      cityArr: [], // 城市列表
      areaArr: [], // 区县列表
      submitType: 0, // 添加-0 修改-1
      isEdit: 1 // 0-不取消 1-取消
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.initDistPicker();
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.getAdsList();
  },
  //方法
  methods: {
    // 获取地址列表
    getAdsList() {
      const that = this;
      this.$postRequest("/api/member/address/list", {
        userId: localStorage.getItem("userId")
      }).then(res => {
        that.adsList = res.data;
      })
    },
    // 打开添加
    editAddress(type) {
      this.dialogFormVisible = true;
      this.submitType = 0;
      this.restForm();
    },
    // 打开编辑
    handleEdit(row) {
      this.dialogFormVisible = true;
      this.submitType = 1;

      this.form = row;
      this.form.provinceCityArea = [];
      this.form.default = JSON.stringify(row.defaultValue);
      this.isCity(this.form);

    },
    // 取消
    cancleSubmit() {
      this.dialogFormVisible = false;
    },
    alog(e) {
      this.$forceUpdate();
    },
    // 提交地址按钮
    adsSubmit() {
      var value = this.form;
      var phoneReg = /^1[0-9]{10}$/;
      if (value.provinceCityArea.length < 3 || value.address == "" || value.fullName == "" || value.phone == "") {
        this.$message.error("请将信息补充完整");
      } else if (!phoneReg.test(value.phone)) {
        this.$message.error("手机号有误，请确认后重新提交");
      } else {
        if (this.submitType == 0) {
          this.addAds();
        } else if (this.submitType == 1) {
          var adsId = this.form.id;
          this.editAds(adsId);
        }
      }
    },
    // 新增地址
    addAds() {
      const that = this;
      this.$postRequest("/api/member/address/add", {
        userId: localStorage.getItem("userId"),
        province: this.form.province,
        city: this.form.city,
        county: this.form.county,
        address: this.form.address,
        fullName: this.form.fullName,
        phone: this.form.phone,
        default: this.form.default
      }).then(res => {
        that.$message.success("添加成功")
        that.dialogFormVisible = false;
        that.restForm();
        that.getAdsList();
      })
    },
    // 修改地址
    editAds(id) {
      const that = this;
      this.$postRequest("/api/member/address/change", {
        userId: localStorage.getItem("userId"),
        province: this.form.province,
        city: this.form.city,
        county: this.form.county,
        address: this.form.address,
        fullName: this.form.fullName,
        phone: this.form.phone,
        default: this.form.default,
        addressId: id
      }).then(res => {
        that.$message.success("修改成功")
        that.dialogFormVisible = false;
        that.restForm();
        that.getAdsList();
      })
    },
    // 清空表单
    restForm() {
      this.form = {
        provinceCityArea: "",
        address: "",
        province: "",
        city: "",
        county: "",
        fullName: "",
        phone: "",
        default: "1",
      }
    },
    // 删除地址
    handleDelete(row) {
      this.$confirm('是否确认删除该地址?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const that = this;
        this.$postRequest("/api/member/address/remove", {
          userId: localStorage.getItem("userId"),
          addressId: row.id
        }).then(res => {
          that.$message.success("删除成功");
          that.getAdsList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    // 设置默认地址
    moren(row) {
      const that = this;
      this.$postRequest("/api/member/address/default", {
        userId: localStorage.getItem("userId"),
        addressId: row.id
      }).then(res => {
        that.$message.success("设置成功");
        that.getAdsList();
      })
    },
    // 初始化选择器
    initDistPicker() {
      let distData = arr.arr;
      let options = []; // 省
      for (var provinceKy in distData["100000"]) {
        let optProvinceItem = {
          value: provinceKy,
          label: distData["100000"][provinceKy]
        };
        if (distData[provinceKy]) {
          // 市
          for (var cityKy in distData[provinceKy]) {
            optProvinceItem.children = optProvinceItem.children
              ? optProvinceItem.children
              : [];
            let optCityItem = {
              value: cityKy,
              label: distData[provinceKy][cityKy]
            };
            if (distData[cityKy]) {
              // 区
              for (var areaKy in distData[cityKy]) {
                optCityItem.children = optCityItem.children
                  ? optCityItem.children
                  : [];
                let optAreaItem = {
                  value: areaKy,
                  label: distData[cityKy][areaKy]
                };
                optCityItem.children.push(optAreaItem);
              }
            }
            optProvinceItem.children.push(optCityItem);
          }
        }
        options.push(optProvinceItem);
      }
      this.distData = distData;
      this.options = options;
    }, // 切换城市
    changeCity(value) {
      this.options.map((item, index) => {
        if (item.value == value[0]) {
          console.log(item);
          this.cityArr = item.children; //存储城市列表
          this.form.province = item.label;
        }
      }); //获取市名
      this.cityArr.map((item, index) => {
        if (item.value == value[1]) {
          console.log(item);
          this.areaArr = item.children; //存储区县列表
          this.form.city = item.label;
        }
      }); //获取区县名
      this.areaArr.map((item, index) => {
        if (item.value == value[2]) {
          console.log(item);
          this.form.county = item.label;
        }
      });
    },
    // 判断是否有城市(有的话转码)
    isCity(row) {
      this.options.map((item, index) => {
        if (item.label == row.province) {
          this.cityArr = item.children; //存储城市列表
          row.provinceCityArea[0] = item.value;
        }
      })
      //获取市名
      this.cityArr.map((item, index) => {
        if (item.label == row.city) {
          this.areaArr = item.children; //存储区县列表
          row.provinceCityArea[1] = item.value;
        }
      });
      //获取区县名
      this.areaArr.map((item, index) => {
        if (item.label == row.county) {
          row.provinceCityArea[2] = item.value;
        }
      });
    }
  }
}
</script>
<style scoped lang='scss'>
/deep/ .el-cascader .el-input .el-input__inner {
  width: 300px;
}
.in {
  width: 100%;
  overflow-y: auto;
  background: #ffffff;
  border: 1px solid #eeeeee;
  .tit {
    width: 100%;
    height: 50px;
    background: #ffffff;
    border-bottom: 1px solid #eeeeee;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .ul1 {
      display: flex;
      height: 100%;
      align-items: center;
      div {
        height: 50px;
        line-height: 50px;
        text-align: center;
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #000000;
        margin-left: 20px;
      }
    }
    .ul2 {
      padding-right: 20px;
      cursor: pointer;
      color: #1a69e0;
      display: flex;
      align-items: center;
      .img {
        width: 20px;
        height: 20px;
        margin-right: 8px;
      }
      &:hover {
        opacity: 0.8;
      }
    }
  }
  .qie {
    padding: 20px;
    .one {
      height: 14px;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #666666;
    }
    .tab {
      border: 1px solid #eeeeee;
      border-bottom: none;
      margin: 20px 0;
    }
  }
}
</style>